package beans.thread.hebeiguoshui;

import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

import beans.bytee.ByteUtils;

/**
 * 短连接 demo
 * 
 * 给河北国税写的例子。
 * 
 * @author Jert
 * 
 */
public class Server extends Thread
{
	private final Socket s;

	public Server(Socket s)
	{
		this.s = s;
	}

	public static void main(String[] args)
	{
		try
		{
			ServerSocket ss = new ServerSocket(9098);
			Socket s = ss.accept();
			new Server(s).start();
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}
	}

	@Override
	public void run()
	{
		try
		{
			InputStream is = s.getInputStream();

			DataInputStream dis = new DataInputStream(new BufferedInputStream(is));

			byte[] length = new byte[4];
			for (int i = 0; i < 4; i++)
			{
				length[i] = dis.readByte();
			}

			// byte[] 转换成int
			int l = ByteUtils.readInt(length, 0);
			System.out.println(l);

			StringBuffer sb = new StringBuffer();
			for (int i = 0; i < l; i++)
			{
				char c = (char) dis.read();
				sb.append(c);
			}
			if (is != null)
				is.close();
			System.out.println(">>>>>>>>>" + sb);
			System.out.println("关闭线程");
			if (dis != null)
				dis.close();
			if (!s.isClosed())
				s.close();

		}
		catch (IOException e)
		{
			e.printStackTrace();
		}
	}

}
